<template>
  <div>
    <el-form ref="addFormRef" :rules="rules" :model="addForm.data" label-width="120">
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="addForm.data.realName"
          style="width: 320px"
          minlength="2"
          maxlength="10"
          placeholder="请输入真实姓名"
        />
      </el-form-item>
      <el-form-item label="登录账号" prop="userName">
        <el-input
          v-model="addForm.data.userName"
          style="width: 320px"
          placeholder="请输入登录账号"
          @input="handleInput(addForm.data.userName)"
        />
        <div
          v-if="userNameFlag"
          style="font-size: 12px; color: #f56c6c; height: 14px; margin-top: -8px"
        >
          已有账号，请重新设置！
        </div>
      </el-form-item>

      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="addForm.data.phone"
          style="width: 320px"
          maxlength="11"
          placeholder="请输入手机号码"
        />
      </el-form-item>
      <el-form-item label="电子邮箱">
        <el-input
          v-model="addForm.data.email"
          placeholder="请输入电子邮箱"
          style="width: 320px"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="addForm.data.deptId"
          :data="department.data"
          :props="defaultProps"
          :render-after-expand="false"
          check-strictly
          style="width: 320px"
          placeholder="请选择所属部门"
        />
      </el-form-item>
      <el-form-item label="角色">
        <el-cascader
          v-model="addForm.data.roleIds"
          :options="roleList.data"
          style="width: 320px"
          placeholder="请选择角色"
          :props="{
            value: 'id',
            label: 'name',
            multiple: true,
          }"
          @change="handleCascaderChange"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <div class="footer">
          <div></div>
          <div>
            <el-button class="reset-btn" @click="resetForm(addFormRef)">重 置</el-button>
            <el-button class="confirm-btn" @click="submitForm(addFormRef)"
              >确 认</el-button
            >
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from "vue";
import {
  getDepartment,
  getRole,
  getAddCashier,
} from "../request.js";

const department = reactive({
  data: [],
});

const defaultProps = {
  children: "nodes",
  label: "name",
  value: "id",
};

const getDepartmentData = async () => {
  await getDepartment().then((res) => {
    console.log("res ===>", res);
    department.data = res.data.result;
  });
};
getDepartmentData();

const roleList = reactive({
  data: [],
});

const getRoleData = async () => {
  await getRole().then((res) => {
    console.log("res ===>", res);
    roleList.data = res.data.result;
  });
};

getRoleData();

const addFormRef = ref("");

const addForm = reactive({
  data: {
    realName: "",
    userName: "",
    phone: "",
    email: "",
    deptId: "",
    roleIds: [],
  },
});

const handleCascaderChange = (value) => {
  console.log("value ===>", value);
  addForm.data.roleIds = addForm.data.roleIds
    .filter((item) => Array.isArray(item)) // 确保是数组
    .map((item) => item[0]);
  console.log("value ===>", addForm.data.roleIds);
};

const userNameFlag = ref(false);

const handleInput = (value) => {
  console.log("userName ===>", value);
  // 使用正则表达式限制只能输入字母和数字
  const pattern = /^[A-Za-z0-9]+$/;
  if (pattern.test(value)) {
    // 如果输入值符合正则表达式的规则，则设置为 value 的值
    addForm.data.userName = value;
  } else {
    // 立即删除所有不符合规则的字符
    addForm.data.userName = value.replace(/[^A-Za-z0-9]/g, "");
  }
};

const rules = reactive({
  realName: [
    {
      required: true,
      message: "请输入真实姓名",
      trigger: "blur",
    },
    {
      min: 2,
      max: 10,
      message: "长度在 2 到 10 个字符",
      trigger: "blur",
    },
  ],
  userName: [
    {
      required: true,
      message: "请输入登录账号",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号码",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确，请重新输入",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "请选择所属部门",
      trigger: "change",
    },
  ],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      getAddCashier(addForm.data).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          emits("operationDone");
        } else {
          if (res.data.msg === "用户名重复") {
            console.log("1 ===>", 1);

            userNameFlag.value = true;
          }
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  addForm.data = {};
  formEl.resetFields();
};

const emits = defineEmits(["operationDone"]);
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
</style>
